﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using MLY.Bll;
namespace MLY.LTR
{
  public partial class AttachmentManager : Bll.BasePage
  {
    public bool _userValid = true;
    public int woId
    {
      get
      { return Session["woId"] == null ? -1 : (int)Session["woId"]; }
      set
      {
        Session["woId"] = value;
      }
    }
    void validateUser()
    {
      if (woId == -1)
      {
        try
        {

          int s = int.Parse(Request.QueryString["woId"].ToString());
          Bll.clsWorkOrder w = new MLY.Bll.clsWorkOrder(s);
          if (w.Data.ContractorId != Utils._orgId && w.Data.CustomerId != Utils._orgId)
            throw new Exception("You Are Not Allowed To View This Page!");
          woId = s;
        }
        catch //(Exception ex)
        {
          showErrorMsg("a problem occured on viewing this page!");
          _userValid = false;
        }
      }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      validateUser();
    }

    public string currPath
    {
      get
      {
        return String.Format(@"{0}\{1}",
            Server.MapPath("~") + Utils.AppSettings("AttachmentDirectory"),
            "WO" + woId);
      }
    }

    protected void uploadTool_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
      HttpPostedFile fileToUpload = uploadTool.PostedFile;
      Directory.CreateDirectory(currPath);
      uploadTool.SaveAs(currPath + @"\" + fileToUpload.FileName);

      filesGridView.DataBind();
    }

    protected void filesDs_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
      DirectoryInfo di = new DirectoryInfo(currPath);
      if (!di.Exists)
        di.Create();
      e.Result = di.GetFiles();

    }



    protected void filesGridView_SelectedIndexChanged(object sender, EventArgs e)
    {
      FileInfo f = (FileInfo)filesGridView.SelectedRow.DataItem;
    }

    protected void filesDs_Deleting(object sender, LinqDataSourceDeleteEventArgs e)
    {
      FileInfo f = (FileInfo)e.OriginalObject;
      f.Delete();
      filesGridView.DataBind();
      e.Cancel = true;

    }

    protected void filesGridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      FileInfo f = new FileInfo(currPath + @"\" + e.CommandArgument);
      switch (e.CommandName.ToLower())
      {
        case "filedelete":
          f.Delete();
          filesGridView.DataBind();

          break;
        case "filedownload": sendFile(f);

          break;
      }
    }

    void sendFile(FileInfo file)
    {
      System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
      FileStream f = file.OpenRead();
      byte[] buffer = new byte[f.Length];
      f.Read(buffer, 0, int.Parse(f.Length.ToString()));

      Response.Clear();
      Response.ContentType = "application/octet-stream";
      Response.AddHeader("Content-Length", buffer.Length.ToString());
      Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.Name.Replace(' ', '-'));
      Response.BinaryWrite(buffer);
      Response.End();



    }
  }
}
